package com.bw.kotlindemo.java.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;


import com.bw.kotlindemo.R;
import com.bw.kotlindemo.databinding.ItemLiveListBinding;
import com.bw.kotlindemo.java.model.bean.LiveListBean;
import com.bw.kotlindemo.java.utils.ImgLoadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * desc:
 * create by xushaodong on 2023/3/22
 */
public class LiveListAdapter extends RecyclerView.Adapter<LiveListAdapter.LiveListHolder> {
    private Context context;
    private List<LiveListBean.ResultBean> data = new ArrayList<>();
    public LiveListAdapter(Context context){
        this.context = context;
    }

    @NonNull
    @Override
    public LiveListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_live_list,parent,false);
        return new LiveListHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull LiveListHolder holder, int position) {

        if(position < 0 || position >= data.size()){
            return;
        }
        if(holder != null){
            LiveListBean.ResultBean resultBean = data.get(position);
            holder.bind(resultBean);
            holder.tv_title.setText(resultBean.getNickName());
            ImgLoadUtils.loadImg(context,resultBean.getLiveCoverUrl(),holder.binding.img);
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    //设置数据
    public void setData(List<LiveListBean.ResultBean> result) {
        if(result != null){
            //1.先清空集合
            data.clear();
            //2.然后再添加数据
            data.addAll(result);
            //3.刷新列表
            notifyDataSetChanged();
        }
    }

    //优化后的方法，大家灵活运用
    public void addData(List<LiveListBean.ResultBean> result) {
        int pos = data.size() +1;
        data.addAll(result);
        notifyItemRangeInserted(pos,result.size());
    }

    static class LiveListHolder extends RecyclerView.ViewHolder{
        TextView tv_title;
        ItemLiveListBinding binding;

        public LiveListHolder(@NonNull View itemView) {
            super(itemView);
            tv_title = itemView.findViewById(R.id.tv_title);
            binding = DataBindingUtil.bind(itemView);
        }

        public void bind(LiveListBean.ResultBean liveTestBean){
            binding.setLiveBean(liveTestBean);
        }
    }
}
